<?php


namespace app\Common;

/**短信服务
 * Class ShortMsg
 * @package app\Common
 */
class ShortMsg
{
    private $_platConf = ['tx']; // 可选择短信平台

    /**发送短信
     * @param $plat
     * @param $code
     * @param $expire
     * @param $mobile
     * @return array
     */
    public function send($plat, $code, $expire, $mobile)
    {
        switch ($plat) {
            case 'tx':
                $conf = config('tools.shortMsg.tx');
                if ($conf == null) return ['code' => 400, 'msg' => '请检查您的配置文件config/tools', 'data' => []];
                // 云市场分配的密钥Id
                if (isset($conf['secretID'])) {
                    $secretId = $conf['secretID'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少secretID', 'data' => []];
                }
                // 云市场分配的密钥Key
                if (isset($conf['secretKey'])) {
                    $secretKey = $conf['secretKey'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少secretKey', 'data' => []];
                }
                $source = 'market';
                // 签名
                $datetime = gmdate('D, d M Y H:i:s T');
                $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
                $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
                $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

                // 请求方法
                $method = 'POST';
                // 请求头
                $headers = array(
                    'X-Source' => $source,
                    'X-Date' => $datetime,
                    'Authorization' => $auth,
                );
                // 查询参数
                $queryParams = array (
                );
                // body参数（POST方法下）
                $bodyParams = [];
                if (isset($conf['account'])) {
                    $bodyParams['account'] = $conf['account'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少account', 'data' => []];
                }
                if (isset($conf['template'])) {
                    $content = str_replace(['{1}', '{2}'], [$code, $expire], $conf['template']);
                    $bodyParams['content'] = $content;
                } else {
                    return ['code' => 400, 'msg' => '配置缺少content', 'data' => []];
                }
                if (isset($conf['extno'])) {
                    $bodyParams['extno'] = $conf['extno'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少extno', 'data' => []];
                }
                    $bodyParams['mobile'] = $mobile;

                if (isset($conf['password'])) {
                    $bodyParams['password'] = $conf['password'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少password', 'data' => []];
                }
                if (isset($conf['rt'])) {
                    $bodyParams['rt'] = $conf['rt'];
                } else {
                    return ['code' => 400, 'msg' => '配置缺少rt', 'data' => []];
                }
                // url参数拼接
                $url = 'http://service-8opui4qv-1259721353.ap-shanghai.apigateway.myqcloud.com/release/smssend';
                if (count($queryParams) > 0) {
                    $url .= '?' . http_build_query($queryParams);
                }

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
                    return $k . ': ' . $v;
                }, array_values($headers), array_keys($headers)));
                if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
                }

                $data = curl_exec($ch);
                if (curl_errno($ch)) {
                    curl_close($ch);
                    return ['code' => 400, 'msg' => curl_error($ch), 'data' => []];
                } else {
                    curl_close($ch);
                    $data = json_decode($data, true);
                    switch ($data['status']) {
                        case 0:
                            return ['code' => 200, 'msg' => '发送成功', 'data' => []];
                        case 1:
                            return ['code' => 400, 'msg' => '消息包格式错误', 'data' => []];
                        case 2:
                            return ['code' => 400, 'msg' => 'IP鉴权错误', 'data' => []];
                        case 3:
                            return ['code' => 400, 'msg' => '账号密码不正确', 'data' => []];
                        case 4:
                            return ['code' => 400, 'msg' => '版本号错误', 'data' => []];
                        case 5:
                            return ['code' => 400, 'msg' => '其它错误', 'data' => []];
                        case 6:
                            return ['code' => 400, 'msg' => '接入点错误', 'data' => []];
                        case 7:
                            return ['code' => 400, 'msg' => '账号状态异常', 'data' => []];
                        case 15:
                            return ['code' => 400, 'msg' => '余额不足', 'data' => []];
                        default:
                            return ['code' => 400, 'msg' => '未知错误', 'data' => []];
                    }
                }
                break;
            default:
                return ['code' => 400, 'msg' => '不可用的短信平台', 'data' => []];
        }
    }
}